//
//  GesturePwdViewController.m
//  NOAHWM
//
//  Created by Ryan on 13-6-3.
//  Copyright (c) 2013年 Ryan. All rights reserved.
//

#import "GesturePwdViewController.h"
#import "ShakingAlertView.h"
#import "NYMemberCenterDataManager.h"
#import "NSString+MD5.h"
#import "JSON.h"
#import "PatternLockPwdManager.h"

#define kOpenImageName  @"switch1_highlighted@2x"
#define kCloseImageName @"switch1_normal@2x"

#define kChangeLockStateDownloderKey    @"ChangeLockStateDownloderKey"
#define kAuthLoginPasswordDownloaderKey @"AuthLoginPasswordDownloaderKey"

@interface GesturePwdViewController ()

@property (nonatomic, retain) ShakingAlertView *shakingAlertView;
@property (nonatomic, assign) UIButton *switchButton;
@property (nonatomic, assign) BOOL isChangeStatus;

@end

@implementation GesturePwdViewController

@synthesize myTableView;
@synthesize shakingAlertView;
@synthesize switchButton;
@synthesize isChangeStatus;

- (ShakingAlertView *)shakingAlertView
{
    if(nil == shakingAlertView)
    {
        shakingAlertView = [[ShakingAlertView alloc] initWithAlertTitle:@"设置手势密码前登录验证"
                                                       checkForPassword:nil];
        
        // Block to excute on success
        [shakingAlertView setOnCorrectPassword:^(NSString *text){
            // Show a modal view
            NSString *md5pwd = [NSString md5HexDigest:text];
            NSString *suburl = [NSString stringWithFormat:kPwdAuthUrl,@"jsonp",[NYMemberCenterDataManager sharedManager].loginMember.accountId,md5pwd];
            suburl = [suburl stringByAppendingString:@"app000013"];
            NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
            url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:kAuthLoginPasswordDownloaderKey];
        }];
        
        // Block to execute on alert dismissal
        [shakingAlertView setOnDismissalWithoutPassword:^{
            // Show regular UIAlertView to give them another go
            if(self.isChangeStatus)
                self.switchButton.enabled = YES;
        }];
    }
    return shakingAlertView;
}

- (void)gesturePwdSwitch
{
    self.switchButton.enabled = NO;
    self.isChangeStatus = YES;
    [self.shakingAlertView show];
}

- (void)changeGestureStatus
{
    //用户输入登录验证通过之后可以直接修改手势密码开关状态
    NSInteger on;
    if(self.switchButton.tag == 1)
    {
        //当前手势处于打开状态-点击之后关闭
        on = 0;
    }
    else
    {
        //当前手势处于关闭状态-点击之后打开
        on = 1;
    }
    NSString *suburl = [NSString stringWithFormat:kSaveGestureStateUrl,@"jsonp",[NYMemberCenterDataManager sharedManager].loginMember.accountId,on];
    suburl = [suburl stringByAppendingString:@"app000012"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:kChangeLockStateDownloderKey];
}

#pragma mark - BaseViewController methods
- (void)leftItemTapped
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIViewController methods
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.myTableView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    if(self.navigationController.presentingViewController)
    {
        //当从手势密码页面push出当前页面
        [self addSwipePopGesture];
    }
    
    [self setNaviTitle:@"手势密码"];
    [self setLeftNaviItemWithTitle:nil imageName:@"Icon_Back"];
    [self setRightNaviItemWithTitle:nil imageName:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.isViewLoaded && !self.view.window)
    {
        [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
        self.view = nil;
        self.myTableView = nil;
    }
}

- (void)viewDidUnload
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    self.myTableView = nil;
    [super viewDidUnload];
}

- (void)dealloc
{
    [[RYDownloaderManager sharedManager] cancelDownloaderWithDelegate:self purpose:nil];
    [shakingAlertView release];
    [myTableView release];
    [super dealloc];
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"cellIdentify";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if(nil == cell)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify] autorelease];
        
        UIImageView *bgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_selection@2x.png"]];
        cell.selectedBackgroundView = bgView;
        [bgView release];
        cell.textLabel.highlightedTextColor = [UIColor blackColor];
        
    }
    if(indexPath.row == 0)
    {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.text = @" 开关";
        
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(250.f, 9.f, 40.f, 40.f)];
        self.switchButton = btn;
        [btn addTarget:self action:@selector(gesturePwdSwitch) forControlEvents:UIControlEventTouchUpInside];
        
        /**使用button.tag来标识当前的手势开关状态
            1 - 打开
            0 - 关闭
         */
        if([[PatternLockPwdManager sharedManager].lockMember gestureOpen])
        {
            [btn setImage:[UIImage imageNamed:kOpenImageName] forState:UIControlStateNormal];
            btn.tag = 1;
        }
        else
        {
            [btn setImage:[UIImage imageNamed:kCloseImageName] forState:UIControlStateNormal];
            btn.tag = 0;
        }
        [cell.contentView addSubview:btn];
        [btn release];
    }
    else
    {
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        cell.textLabel.text = @" 重置";
    }
    cell.textLabel.font = [UIFont systemFontOfSize:16.f];
    return cell;
}


#pragma mark - UITableViewDelegate methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
        return;
    else
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        self.isChangeStatus = NO;
        [self.shakingAlertView show];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    
    if([downloader.purpose isEqualToString:kAuthLoginPasswordDownloaderKey])
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            if(!self.isChangeStatus)
            {
                //点击重置同时验证成功，打开设置手势密码页
                [[NSNotificationCenter defaultCenter] postNotificationName:kShowPatternLockViewNotification object:[NSNumber numberWithInt:0]];
            }
            else
            {
                [self changeGestureStatus];
            }
        }
        else
        {
            if(self.isChangeStatus)
                self.switchButton.enabled = YES;
            [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
        }
    }
    else
    {
        NSDictionary *dict = [str JSONValue];
        if([[dict objectForKey:@"result"] isEqualToString:@"1"])
        {
            //手势密码设置成功
            if(self.switchButton.tag == 1)
            {
                //从手势密码打开状态关闭
                [NYMemberCenterDataManager sharedManager].loginMember.is_gesture_password = @"0";
                self.switchButton.tag = 0;
                [self.switchButton setImage:[UIImage imageNamed:kCloseImageName] forState:UIControlStateNormal];
            }
            else
            {
                //从手势密码关闭状态打开
                [NYMemberCenterDataManager sharedManager].loginMember.is_gesture_password = @"1";
                self.switchButton.tag = 1;
                [self.switchButton setImage:[UIImage imageNamed:kOpenImageName] forState:UIControlStateNormal];
            }
        }
        else
        {
            [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
        }
        self.switchButton.enabled = YES;
    }
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    if([downloader.purpose isEqualToString:kAuthLoginPasswordDownloaderKey])
    {
        [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
    }
    else
    {
        [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
        self.switchButton.enabled = YES;
    }
}
@end
